package sample;

import java.awt.Color;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

import robocode.HitRobotEvent;
import robocode.HitWallEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;
import utfpr.si.connection.Client;
import utfpr.si.interfaces.IntServidor;

public class RoboScannerB extends Robot {

	private Client cli;
	private IntServidor refServer;

	public RoboScannerB(){
        System.out.println("iniciou o Robo Scanner");
        try {
            cli = new Client(1313,"localhost");
            cli.initClient();
            refServer = cli.getRefServer();
        } catch (RemoteException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
	}

	@Override
	public void run() {
		setBodyColor(Color.YELLOW);
		setScanColor(Color.YELLOW);
		setRadarColor(Color.GREEN);

		
		double d = getHeading();
		if( d > 180 ) turnRight(360.0-getHeading());
		else turnLeft(getHeading());
		ahead( -getY() );

		boolean right = false;
		while(true){
			if( !right ){
				turnRadarRight(90.0);
				right = true;
			}else{
				turnRadarLeft(90.0);
				right = false;
			}
			
			try {
				Thread.sleep(150);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onScannedRobot(ScannedRobotEvent event) {
		System.out.println(event.getName());
		if( !event.getName().equals("sample.RoboA1") ){
			double b = event.getBearing();
			if( b < 0 ) b = Math.abs(b);
			else b = 360.0 - b;
			double targetX = this.getX()+event.getDistance()*Math.cos(Math.toRadians(b));
			double targetY = this.getY()+event.getDistance()*Math.sin(Math.toRadians(b));
			System.out.println(event.getName()+" ("+targetX+","+targetY+")");
			try {
				refServer.updateTable(event.getName(), targetX, targetY);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onHitRobot(HitRobotEvent event) {
		double r = Math.random();
		if( r > 0.5 ){
			turnLeft(90.0);
			ahead(getWidth()*2.0);
			turnRight(90.0);
		}else{
			turnRight(90.0);
			ahead(getWidth()*2.0);
			turnLeft(90.0);
		}
		ahead( -getY() );
	}

	@Override
	public void onHitWall(HitWallEvent event) {
		turnLeft(90.0);
		ahead(-(this.getBattleFieldWidth() - getX() - getWidth()/2.0));
	}
	
}
